#include"mystdio.h"
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<string.h>
#include<stdlib.h>
#include<unistd.h> 

static MyFile* BuyFile(int fd, int flag)
{
    MyFile* f = (MyFile*)malloc(sizeof(MyFile));
    if(f == NULL) return NULL;

    f->bufferlen = 0;
    f->fileno = fd;
    f->flag = flag;
    f->flush_method = LINE_FLUSH;
    memset(f->buffer, 0, sizeof(f->bufferlen));

    return f;
}

MyFile* MyFopen(const char* path, const char* mode)
{
    int fd = -1, flag = 0;
    if(strcmp(mode, "w"))
    {
        flag = O_CREAT | O_WRONLY | O_TRUNC;
        fd = open(path, flag, 0666);
    }
    else if(strcmp(mode, "a"))
    { 
        flag = O_CREAT | O_WRONLY | O_APPEND;
        fd = open(path, flag, 0666);
    }
    else if(strcmp(mode, "r"))
    {
        flag = O_RDONLY;
        fd = open(path, flag);
    }

    if(fd < 0) return NULL;
    
    return BuyFile(fd, flag);
}

void MyFclose(MyFile* file)
{
    
}

int MyFwrite(MyFile* file, const void* str, int len)
{
    //拷贝
    memcpy(file->buffer + file->bufferlen, str, len);
    file->bufferlen += len;

    //尝试判断是否满足刷新条件 
    if((file->flush_method & LINE_FLUSH) && file->buffer[file->bufferlen - 1] == '\n')
        MyFFulsh(file);

    return 0;
}

void MyFFulsh(MyFile* file)
{
    int n = write(file->fileno, file->buffer, file->bufferlen);
    (void)n;
    file->bufferlen = 0;
}
